﻿!(function (doc, win) {
    var el = doc.documentElement;
    //resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize';

    function setSize() {
        var w = el.clientWidth;
        if (!w) return;
        w = w > 480 ? 480 : w;
        w = w < 320 ? 320 : w;
        el.style.fontSize = (100 * (w / 1080)).toFixed(3) + 'px';
    }
    if (!doc.addEventListener) return;
    setSize();
    win.addEventListener('resize', setSize, false);
    win.addEventListener('pageshow', function (e) {
        if (e.persisted) {
            setSize();
        }
    }, false);
})(document, window);

//header 菜单
$(function () {
    var banner = new Swiper('.banner', {
        autoplay: 5000,
        pagination: '.swiper-pagination',
        paginationClickable: true,
        lazyLoading: true,
        loop: true
    });

    $('a.slide-menu').on('click', function (e) {
        var wh = $('div.wrapper').height();
        $('div.slide-mask').css('height', wh).show();
        $('aside.slide-wrapper').css('height', wh).addClass('moved');
    });

    $('div.slide-mask').on('click', function () {
        $('div.slide-mask').hide();
        $('aside.slide-wrapper').removeClass('moved');
    });
});

//描 述：基础操作类--top 是Window默认的全局变量，在全局变量上扩展操作对象
top.ibpm = (function ($) {
    "use strict";   //严格模式
    var ibpm = {
        log: function () {
            console.log('=====>' + new Date().getTime() + '<=====');
            var len = arguments.length;
            for (var i = 0; i < len; i++) {
                console.log(arguments[i]);
            }
        },
        // 创建一个GUID
        newGuid: function () {
            var guid = "";
            for (var i = 1; i <= 32; i++) {
                var n = Math.floor(Math.random() * 16.0).toString(16);
                guid += n;
                if ((i == 8) || (i == 12) || (i == 16) || (i == 20)) guid += "-";
            }
            return guid;
        },
        // 改变url参数值
        changeUrlParam: function (url, key, value) {
            var newUrl = "";
            var reg = new RegExp("(^|)" + key + "=([^&]*)(|$)");
            var tmp = key + "=" + value;
            if (url.match(reg) != null) {
                newUrl = url.replace(eval(reg), tmp);
            } else {
                if (url.match("[\?]")) {
                    newUrl = url + "&" + tmp;
                }
                else {
                    newUrl = url + "?" + tmp;
                }
            }
            return newUrl;
        },
        // 转化成十进制
        toDecimal: function (num) {
            if (num == null) {
                num = "0";
            }
            num = num.toString().replace(/\$|\,/g, '');
            if (isNaN(num))
                num = "0";
            var sign = (num == (num = Math.abs(num)));
            num = Math.floor(num * 100 + 0.50000000001);
            var cents = num % 100;
            num = Math.floor(num / 100).toString();
            if (cents < 10)
                cents = "0" + cents;
            for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
                num = num.substring(0, num.length - (4 * i + 3)) + '' +
                    num.substring(num.length - (4 * i + 3));
            return (((sign) ? '' : '-') + num + '.' + cents);
        },
        // 文件大小转换
        countFileSize: function (size) {
            if (size < 1024.00)
                return ibpm.toDecimal(size) + " 字节";
            else if (size >= 1024.00 && size < 1048576)
                return ibpm.toDecimal(size / 1024.00) + " KB";
            else if (size >= 1048576 && size < 1073741824)
                return ibpm.toDecimal(size / 1024.00 / 1024.00) + " MB";
            else if (size >= 1073741824)
                return ibpm.toDecimal(size / 1024.00 / 1024.00 / 1024.00) + " GB";
        },
        // 数组复制
        arrayCopy: function (data) {
            return $.map(data, function (obj) {
                return $.extend(true, {}, obj);
            });
        },
        //下载文件（she写的扩展）
        download: function (options) {
            var defaults = {
                method: "GET",
                url: "",
                param: []
            };
            var options = $.extend(defaults, options);
            if (options.url && options.param) {
                var $form = $('<form action="' + options.url + '" method="' + (options.method || 'post') + '"></form>');
                for (var key in options.param) {
                    var $input = $('<input type="hidden" />').attr('name', key).val(options.param[key]);
                    $form.append($input);
                }
                $form.appendTo('body').submit().remove();
            };
        },
        // 数字格式转换成千分位
        commafy: function (num) {
            if (num == null) {
                num = "0";
            }
            if (isNaN(num)) {
                return "0";
            }
            num = num + "";
            if (/^.*\..*$/.test(num)) {
                varpointIndex = num.lastIndexOf(".");
                varintPart = num.substring(0, pointIndex);
                varpointPart = num.substring(pointIndex + 1, num.length);
                intPart = intPart + "";
                var re = /(-?\d+)(\d{3})/
                while (re.test(intPart)) {
                    intPart = intPart.replace(re, "$1,$2")
                }
                num = intPart + "." + pointPart;
            } else {
                num = num + "";
                var re = /(-?\d+)(\d{3})/
                while (re.test(num)) {
                    num = num.replace(re, "$1,$2")
                }
            }
            return num;
        },
        // 检测图片是否存在
        isExistImg: function (pathImg) {
            if (!!pathImg) {
                var ImgObj = new Image();
                ImgObj.src = pathImg;
                if (ImgObj.fileSize > 0 || (ImgObj.width > 0 && ImgObj.height > 0)) {
                    return true;
                } else {
                    return false;
                }
            }
            else {
                return false;
            }
        }
    };
    return ibpm;
})(window.jQuery);

//ajax操作方法--接着上面的基础定义，追加扩展
(function ($, ibpm) {
    "use strict";
    var httpCode = {
        success: 200,
        fail: 400,
        exception: 500
    };
    var exres = { code: httpCode.exception, info: '通信异常，请联系管理员！' }
    $.extend(ibpm, {
        // http 通信异常的时候调用此方法
        httpErrorLog: function (msg) {
            ibpm.log(msg);
        },
        // http请求返回数据码
        httpCode: httpCode,
        // get请求方法（异步）:url地址,callback回调函数
        httpAsyncGet: function (url, callback) {
            $.ajax({
                url: url,
                type: "GET",
                dataType: "json",
                async: true,
                cache: false,
                success: function (data) {
                    if (data.code == ibpm.httpCode.exception) {
                        ibpm.httpErrorLog(data.info);
                    }
                    else if (data.code == ibpm.httpCode.fail) {
                        ibpm.httpErrorLog(data.info);
                    }
                    else
                        callback(data);
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    ibpm.httpErrorLog(textStatus);
                },
                beforeSend: function (request) {
                    request.setRequestHeader("Authorization", "Bearer " + $.AToken);
                },
                complete: function () {

                }
            });
        },
        // get请求方法（同步）:url地址,param参数
        httpAsyncGetByParam: function (url, param, callback) {
            $.ajax({
                url: url,
                data: param,
                type: "GET",
                dataType: "json",
                async: true,
                cache: false,
                success: function (data) {
                    if (data.code == ibpm.httpCode.exception) {
                        ibpm.httpErrorLog(data.info);
                    }
                    else if (data.code == ibpm.httpCode.fail) {
                        ibpm.httpErrorLog(data.info);
                    }
                    else
                        callback(data);
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    ibpm.httpErrorLog(textStatus);
                },
                beforeSend: function (request) {
                    request.setRequestHeader("Authorization", "Bearer " + $.AToken);
                },
                complete: function () {

                }
            });
        },
        // post请求方法（FromForm）:url地址,param参数,callback回调函数
        httpAsyncPost: function (url, param, callback) {
            $.ajax({
                url: url,
                data: param,
                type: "POST",
                contentType: "application/x-www-form-urlencoded",
                dataType: "json",
                async: true,
                cache: false,
                success: function (data) {
                    if (data.code == ibpm.httpCode.exception) {
                        ibpm.httpErrorLog(data.info);
                    }
                    else if (data.code == ibpm.httpCode.fail) {
                        ibpm.httpErrorLog(data.info);
                    }
                    else
                        callback(data);
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    ibpm.httpErrorLog(textStatus);
                },
                beforeSend: function (request) {
                    request.setRequestHeader("Authorization", "Bearer " + $.AToken);
                },
                complete: function () {

                }
            });
        },
        // post请求方法 FromBody（用于非验证提交）上不了RequestVerificationToken的验证
        httpAsyncPostBody: function (url, param, callback) {
            $.ajax({
                url: url,
                data: JSON.stringify(param),
                type: "POST",
                dataType: "json",
                contentType: "application/json",
                async: true,
                cache: false,
                success: function (data) {
                    if (data.code == ibpm.httpCode.exception) {
                        ibpm.httpErrorLog(data.info);
                    }
                    else if (data.code == ibpm.httpCode.fail) {
                        ibpm.httpErrorLog(data.info);
                    }
                    else
                        callback(data);
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    ibpm.httpErrorLog(textStatus);
                },
                beforeSend: function (request) {
                    request.setRequestHeader("Authorization", "Bearer " + $.AToken);
                },
                complete: function () {

                }
            });
        },
        // post同步
        httpSyncPost: function (url, param) {
            var RD = null;
            function getData(url, param) {
                var defer = $.Deferred();
                $.ajax({
                    url: url,
                    data: param,
                    type: "POST",
                    dataType: "json",
                    async: false,   //要求不能是异步
                    cache: false,
                    success: function (data) {
                        defer.resolve(data);
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        defer.resolve(exres)
                    },
                    beforeSend: function (request) {
                        request.setRequestHeader("Authorization", "Bearer " + $.AToken);
                    },
                    complete: function () {

                    }
                });
                return defer.promise();
            }
            $.when(getData(url, param)).done(function (data) {
                RD = data;
            });
            return RD;
        },
        // ajax 异步封装
        httpAsync: function (mode, url, param, callback) {
            $.ajax({
                url: url,
                data: param,
                type: mode,
                dataType: "json",
                async: true,
                cache: false,
                success: function (res) {
                    if (res.code == ibpm.httpCode.success) {
                        callback(res.data);
                    }
                    else {
                        ibpm.httpErrorLog(res.info);
                        callback(null);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    ibpm.httpErrorLog(textStatus);
                    callback(null);
                },
                beforeSend: function (request) {
                    request.setRequestHeader("Authorization", "Bearer " + $.AToken);
                },
                complete: function () {

                }
            });
        },
        deleteForm: function (url, param, callback) {
            setTimeout(function () {
                ibpm.httpAsyncPost(url, param, function (res) {
                    if (res.code == ibpm.httpCode.success) {
                        if (!!callback) {
                            callback(res);
                        }
                    }
                    layer.close(layer.index);
                });
            }, 500);
        },
        postForm: function (url, param, callback) {
            ibpm.httpAsyncPost(url, param, function (res) {
                if (res.code == ibpm.httpCode.success) {
                    if (!!callback) {
                        callback(res);
                    }
                }
            });
        }
    });
    //参数就是扩展对象
})(window.jQuery, top.ibpm);

//表单处理方法
(function ($, ibpm) {
    "use strict";
    /*获取和设置表单数据*/
    $.fn.ibpm_GetFormData = function () {// 获取表单数据
        var resdata = {};
        $(this).find('input,select,textarea').each(function (r) {
            var id = $(this).attr('id');
            if (!!id) {
                var type = $(this).attr('type');
                switch (type) {
                    case "radio":
                        resdata[id] = $(this).find('input:checked').val();;
                        break;
                    case "checkbox":
                        var _idlist = [];
                        $(this).find('input:checked').each(function () {
                            _idlist.push($(this).val());
                        });
                        resdata[id] = String(_idlist);
                        break;
                    default:
                        var value = $(this).val();
                        resdata[id] = $.trim(value);
                        break;
                }
            }
        });
        return resdata;
    };

})(jQuery, top.ibpm);

//多属性选择框
function toshare() {
    $(".am-share").addClass("am-modal-active");
    if ($(".sharebg").length > 0) {
        $(".sharebg").addClass("sharebg-active");
    } else {
        $("body").append('<div class="sharebg"></div>');
        $(".sharebg").addClass("sharebg-active");
    }
    $(".sharebg-active,.share_btn").click(function () {
        $(".am-share").removeClass("am-modal-active");
        setTimeout(function () {
            $(".sharebg-active").removeClass("sharebg-active");
            $(".sharebg").remove();
        }, 300);
    })
}